package servlet;

import entity.Data;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 */
@WebServlet("/query")
public class QueryServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String spell = request.getParameter("spell");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        List<Data> datas = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,spell,message ")
                    .append(" from t_data ")
                    .append(" where spell like ? ")
                    .append(" or message like ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, "%" + spell + "%");
            ps.setString(2, "%" + spell + "%");
            rs = ps.executeQuery();
            while (rs.next()) {
                Data data = new Data();
                data.setId(rs.getInt("id"));
                data.setSpell(rs.getString("spell"));
                data.setMessage(rs.getString("message"));
                datas.add(data);
            }
            // 将Java的对象集合转换成JSONArray
            JSONArray jsonArray = JSONArray.fromObject(datas);
            out.println(jsonArray.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
